#include "ymodemwindow.h"
#include "ui_ymodemwindow.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QSerialPortInfo>
#include <QSettings>

YmodemWindow::YmodemWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::YmodemWindow),
    serialPort(new QSerialPort),
    ymodemFileTransmit(new YmodemFileTransmit),
    ymodemFileReceive(new YmodemFileReceive)
{
    ui->setupUi(this);

    ui->receivePath->setText(QApplication::applicationDirPath());

    inTransmitting = false;
    inReceiving  = false;

    QSerialPortInfo serialPortInfo;

    foreach (serialPortInfo, QSerialPortInfo::availablePorts()) {
        ui->port->addItem(serialPortInfo.portName());
    }

    serialPort->setPortName("COM1");
    serialPort->setBaudRate(115200);
    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);

    connect(ymodemFileTransmit, YmodemFileTransmit::transmitProgress, this, YmodemWindow::transmitProgress);
    connect(ymodemFileReceive, YmodemFileReceive::receiveProgress, this, YmodemWindow::receiveProgress);
    connect(ymodemFileTransmit, YmodemFileTransmit::transmitStatus, this, YmodemWindow::transmitStatus);
    connect(ymodemFileReceive, YmodemFileReceive::receiveStatus, this, YmodemWindow::receiveStatus);

    loadConfig();
}

YmodemWindow::~YmodemWindow()
{
    delete ui;
    delete serialPort;
    delete ymodemFileTransmit;
    delete ymodemFileReceive;
}

void YmodemWindow::loadConfig()
{
    const QString filename(QApplication::applicationName() + QString(".ini"));

    loadDefaultConfig();
    if(QFile(filename).exists()){
        if(readConfig()){
            return;
        }
    }
//    saveConfig();
}

void YmodemWindow::loadDefaultConfig()
{

}

bool YmodemWindow::readConfig()
{
    const QString filename(QApplication::applicationName() + QString(".ini"));
    QStringList grouplist;
    QString com = "Com";

    QSettings *settings;
    settings = new QSettings(filename, QSettings::IniFormat);
    grouplist = settings->childGroups();
    if(grouplist.contains(com)){
        settings->beginGroup(com);
        if(settings->contains(QString("Port"))){
            ui->port->setCurrentText(settings->value("Port").toString());
        }
        if(settings->contains(QString("BaudRate"))){
            ui->baudRate->setCurrentIndex(settings->value("BaudRate").toInt());
        }
        if(settings->contains(QString("DataBits"))){
//            ui->dataBitsL->setCurrentIndex(settings->value("DataBits").toInt());
        }
        if(settings->contains(QString("Parity"))){
//            ui->parityL->setCurrentIndex(settings->value("Parity").toInt());
        }
        if(settings->contains(QString("StopBits"))){
//            ui->stopBitsL->setCurrentIndex(settings->value("StopBits").toInt());
        }
        settings->endGroup();
    }

    return true;
}

void YmodemWindow::saveConfig()
{
    const QString filename(QApplication::applicationName() + QString(".ini"));

    QSettings *settings;

    settings = new QSettings(filename, QSettings::IniFormat);
    settings->setValue("Com/Port", ui->port->currentText());
    settings->setValue("Com/BaudRate", ui->baudRate->currentIndex());
//    settings->setValue("Com/DataBits", ui->dataBitsL->currentIndex());
//    settings->setValue("Com/Parity", ui->parityL->currentIndex());
//    settings->setValue("Com/StopBits", ui->stopBitsL->currentIndex());

    settings->sync();
}

void YmodemWindow::closeEvent(QCloseEvent *env)
{
    saveConfig();
    QMainWindow::closeEvent(env);
}

void YmodemWindow::on_openBtn_clicked()
{
    if (serialPort->isOpen() == false) {
        serialPort->setPortName(ui->port->currentText());
        serialPort->setBaudRate(ui->baudRate->currentText().toInt());

        if (serialPort->open(QSerialPort::ReadWrite) == true) {
            ui->port->setDisabled(true);
            ui->baudRate->setDisabled(true);
            ui->openBtn->setText(u8"关闭串口");

            ui->transmitBrowse->setEnabled(true);
            ui->receiveBrowse->setEnabled(true);

            if (ui->transmitPath->text().isEmpty() != true) {
                ui->transmitBtn->setEnabled(true);
            }

            if (ui->receivePath->text().isEmpty() != true) {
                ui->receiveBtn->setEnabled(true);
            }
        } else {
            QMessageBox::warning(this, u8"串口打开失败", u8"请检查串口是否已被占用！", u8"关闭");
        }
    } else {
        serialPort->close();

        ui->port->setEnabled(true);
        ui->baudRate->setEnabled(true);
        ui->openBtn->setText(u8"打开串口");

        ui->transmitBrowse->setDisabled(true);
        ui->transmitBtn->setDisabled(true);

        ui->receiveBrowse->setDisabled(true);
        ui->receiveBtn->setDisabled(true);
    }
}

void YmodemWindow::on_transmitBrowse_clicked()
{
    static QString defPath = QApplication::applicationDirPath();
    QString file;
    file = QFileDialog::getOpenFileName(this, u8"打开文件", defPath, "All (*.*)");

    if (file.isEmpty() != true) {
        QFileInfo fi;
        fi.setFile(file);
        defPath = fi.absoluteDir().absolutePath();
        ui->transmitPath->setText(file);
        ui->transmitBtn->setEnabled(true);
    } else {
        ui->transmitBtn->setDisabled(true);
    }
}

void YmodemWindow::on_receiveBrowse_clicked()
{
    static QString defPath = QApplication::applicationDirPath();
    QString dir;
    dir = QFileDialog::getExistingDirectory(this, u8"选择目录", defPath, QFileDialog::ShowDirsOnly);

    if (dir.isEmpty() != true) {
        defPath = dir;
        ui->receivePath->setText(dir);
        ui->receiveBtn->setEnabled(true);
    } else {
        ui->receiveBtn->setDisabled(true);
    }
}

void YmodemWindow::on_transmitBtn_clicked()
{
    if (inTransmitting == false) {
        ymodemFileTransmit->setFileName(ui->transmitPath->text());
        ymodemFileTransmit->setSerialPort(this->serialPort);

        if (ymodemFileTransmit->startTransmit() == true) {
            inTransmitting = true;

            ui->openBtn->setDisabled(true);

            ui->receiveBrowse->setDisabled(true);
            ui->receiveBtn->setDisabled(true);

            ui->transmitBrowse->setDisabled(true);
            ui->transmitBtn->setText(u8"取消");
            ui->transmitProgress->setValue(0);
        } else {
            QMessageBox::warning(this, u8"失败", u8"文件发送失败！", u8"关闭");
        }
    } else {
        ymodemFileTransmit->stopTransmit();
    }
}

void YmodemWindow::on_receiveBtn_clicked()
{
    if (inReceiving == false) {
        ymodemFileReceive->setFilePath(ui->receivePath->text());
        ymodemFileReceive->setSerialPort(this->serialPort);

        if (ymodemFileReceive->startReceive() == true) {
            inReceiving = true;

            ui->openBtn->setDisabled(true);

            ui->transmitBrowse->setDisabled(true);
            ui->transmitBtn->setDisabled(true);

            ui->receiveBrowse->setDisabled(true);
            ui->receiveBtn->setText(u8"取消");
            ui->receiveProgress->setValue(0);
        } else {
            QMessageBox::warning(this, u8"失败", u8"文件接收失败！", u8"关闭");
        }
    } else {
        ymodemFileReceive->stopReceive();
    }
}

void YmodemWindow::transmitProgress(int progress)
{
    ui->transmitProgress->setValue(progress);
}

void YmodemWindow::receiveProgress(int progress)
{
    ui->receiveProgress->setValue(progress);
}

void YmodemWindow::transmitStatus(Ymodem::Status status)
{
    switch(status) {
    case YmodemFileTransmit::StatusEstablish:
    break;
    case YmodemFileTransmit::StatusTransmit:
    break;
    case YmodemFileTransmit::StatusFinish:
    {
        inTransmitting = false;

        ui->openBtn->setEnabled(true);

        ui->receiveBrowse->setEnabled(true);

        if(ui->receivePath->text().isEmpty() != true)
        {
            ui->receiveBtn->setEnabled(true);
        }

        ui->transmitBrowse->setEnabled(true);
        ui->transmitBtn->setText(u8"发送");

        QMessageBox::warning(this, u8"成功", u8"文件发送成功！", u8"关闭");
    }
    break;
    case YmodemFileTransmit::StatusAbort:
    {
        inTransmitting = false;

        ui->openBtn->setEnabled(true);

        ui->receiveBrowse->setEnabled(true);

        if(ui->receivePath->text().isEmpty() != true)
        {
            ui->receiveBtn->setEnabled(true);
        }

        ui->transmitBrowse->setEnabled(true);
        ui->transmitBtn->setText(u8"发送");

        QMessageBox::warning(this, u8"失败", u8"文件发送失败！", u8"关闭");
    }
    break;
    case YmodemFileTransmit::StatusTimeout:
    {
        inTransmitting = false;

        ui->openBtn->setEnabled(true);

        ui->receiveBrowse->setEnabled(true);

        if(ui->receivePath->text().isEmpty() != true)
        {
            ui->receiveBtn->setEnabled(true);
        }

        ui->transmitBrowse->setEnabled(true);
        ui->transmitBtn->setText(u8"发送");

        QMessageBox::warning(this, u8"失败", u8"文件发送失败！", u8"关闭");
    }
    break;
    default:
    {
        inTransmitting = false;

        ui->openBtn->setEnabled(true);

        ui->receiveBrowse->setEnabled(true);

        if(ui->receivePath->text().isEmpty() != true)
        {
            ui->receiveBtn->setEnabled(true);
        }

        ui->transmitBrowse->setEnabled(true);
        ui->transmitBtn->setText(u8"发送");

        QMessageBox::warning(this, u8"失败", u8"文件发送失败！", u8"关闭");
    }
    break;
    }
}

void YmodemWindow::receiveStatus(YmodemFileReceive::Status status)
{
    switch(status) {
    case YmodemFileReceive::StatusEstablish:
    break;
    case YmodemFileReceive::StatusTransmit:
    break;
    case YmodemFileReceive::StatusFinish:
    {
        inReceiving = false;

        ui->openBtn->setEnabled(true);

        ui->transmitBrowse->setEnabled(true);

        if(ui->transmitPath->text().isEmpty() != true)
        {
            ui->transmitBtn->setEnabled(true);
        }

        ui->receiveBrowse->setEnabled(true);
        ui->receiveBtn->setText(u8"接收");

        QMessageBox::warning(this, u8"成功", u8"文件接收成功！", u8"关闭");
    }
    break;
    case YmodemFileReceive::StatusAbort:
    {
        inReceiving = false;

        ui->openBtn->setEnabled(true);

        ui->transmitBrowse->setEnabled(true);

        if(ui->transmitPath->text().isEmpty() != true)
        {
            ui->transmitBtn->setEnabled(true);
        }

        ui->receiveBrowse->setEnabled(true);
        ui->receiveBtn->setText(u8"接收");

        QMessageBox::warning(this, u8"失败", u8"文件接收失败！", u8"关闭");
    }
    break;
    case YmodemFileReceive::StatusTimeout:
    {
        inReceiving = false;

        ui->openBtn->setEnabled(true);

        ui->transmitBrowse->setEnabled(true);

        if(ui->transmitPath->text().isEmpty() != true)
        {
            ui->transmitBtn->setEnabled(true);
        }

        ui->receiveBrowse->setEnabled(true);
        ui->receiveBtn->setText(u8"接收");

        QMessageBox::warning(this, u8"失败", u8"文件接收失败！", u8"关闭");
    }
    break;
    default:
    {
        inReceiving = false;

        ui->openBtn->setEnabled(true);

        ui->transmitBrowse->setEnabled(true);

        if(ui->transmitPath->text().isEmpty() != true)
        {
            ui->transmitBtn->setEnabled(true);
        }

        ui->receiveBrowse->setEnabled(true);
        ui->receiveBtn->setText(u8"接收");

        QMessageBox::warning(this, u8"失败", u8"文件接收失败！", u8"关闭");
    }
    break;
    }
}
